import React from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { 
  BarChart3, 
  TrendingUp, 
  Trophy, 
  Target, 
  Brain, 
  Zap,
  Award,
  Calendar,
  Activity,
  Sword,
  Bot,
  Puzzle,
  Sparkles,
  Smile
} from 'lucide-react';
import { TestResult, UserProfile, Achievement } from '../types';
import { tests, testCategories } from '../constants/tests';

interface DashboardProps {
  testResults: TestResult[];
  userProfile: UserProfile;
  achievements: Achievement[];
  onStartTest: (testType: any) => void;
}

export function Dashboard({ testResults, userProfile, achievements, onStartTest }: DashboardProps) {
  const getPerformanceByCategory = () => {
    const categoryPerformance = Object.entries(testCategories).map(([categoryKey, categoryInfo]) => {
      // 通过测试ID和标题两种方式匹配
      const categoryResults = testResults.filter(result => {
        const test = tests.find(t => 
          t.id === result.testType || 
          t.title === result.testType ||
          result.testType.includes(t.title.replace('测试', ''))
        );
        return test && test.category === categoryKey;
      });
      
      const avgScore = categoryResults.length > 0 
        ? categoryResults.reduce((sum, result) => sum + result.score, 0) / categoryResults.length
        : 0;
      
      return {
        category: categoryKey,
        name: categoryInfo.name,
        score: Math.round(avgScore),
        completed: categoryResults.length,
        total: categoryInfo.tests.length,
        color: categoryInfo.color
      };
    });

    return categoryPerformance;
  };

  const getRecentPerformance = () => {
    const recentTests = testResults
      .filter(result => {
        const testDate = new Date(result.completedAt || result.date || result.timestamp || new Date());
        return testDate instanceof Date && !isNaN(testDate.getTime());
      })
      .sort((a, b) => {
        const dateA = new Date(a.completedAt || a.date || a.timestamp || new Date());
        const dateB = new Date(b.completedAt || b.date || b.timestamp || new Date());
        return dateB.getTime() - dateA.getTime();
      })
      .slice(0, 10);
    
    return recentTests;
  };

  const getStrengthsAndWeaknesses = () => {
    if (testResults.length < 3) return { strengths: [], weaknesses: [] };

    const testScores = testResults.reduce((acc, result) => {
      if (!acc[result.testType]) {
        acc[result.testType] = [];
      }
      acc[result.testType].push(result.score);
      return acc;
    }, {} as Record<string, number[]>);

    const avgScores = Object.entries(testScores).map(([testType, scores]) => ({
      testType,
      avgScore: scores.reduce((sum, score) => sum + score, 0) / scores.length
    }));

    avgScores.sort((a, b) => b.avgScore - a.avgScore);

    const strengths = avgScores.slice(0, 2);
    const weaknesses = avgScores.slice(-2).reverse();

    return { strengths, weaknesses };
  };

  const getProgressOverTime = () => {
    const last30Days = testResults.filter(result => {
      const testDate = new Date(result.completedAt || result.date || result.timestamp || new Date());
      if (!testDate || isNaN(testDate.getTime())) return false;
      const daysDiff = (Date.now() - testDate.getTime()) / (1000 * 60 * 60 * 24);
      return daysDiff <= 30;
    });

    const weeklyData = [];
    for (let i = 0; i < 4; i++) {
      const weekStart = new Date();
      weekStart.setDate(weekStart.getDate() - (i + 1) * 7);
      const weekEnd = new Date();
      weekEnd.setDate(weekEnd.getDate() - i * 7);

      const weekTests = last30Days.filter(result => {
        const testDate = new Date(result.completedAt || result.date || result.timestamp || new Date());
        return testDate >= weekStart && testDate < weekEnd;
      });

      const avgScore = weekTests.length > 0 
        ? weekTests.reduce((sum, result) => sum + result.score, 0) / weekTests.length
        : 0;

      weeklyData.unshift({
        week: `第${4-i}周`,
        score: Math.round(avgScore),
        count: weekTests.length
      });
    }

    return weeklyData;
  };

  const categoryPerformance = getPerformanceByCategory();
  const recentTests = getRecentPerformance();
  const { strengths, weaknesses } = getStrengthsAndWeaknesses();
  const progressData = getProgressOverTime();
  const unlockedAchievements = achievements.filter(a => a.unlocked);
  
  // AI对战统计
  const aiBattleResults = testResults.filter(r => r.details?.battleMode);
  const aiBattleWins = aiBattleResults.filter(r => r.details?.winner === 'player').length;
  const aiBattleWinRate = aiBattleResults.length > 0 ? Math.round((aiBattleWins / aiBattleResults.length) * 100) : 0;

  return (
    <div className="space-y-8">
      {/* Overview Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className="bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-950 dark:to-blue-900">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-blue-600 dark:text-blue-400">总测试数</p>
                <p className="text-3xl font-bold text-blue-700 dark:text-blue-300">{testResults.length}</p>
              </div>
              <BarChart3 className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-br from-green-50 to-green-100 dark:from-green-950 dark:to-green-900">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-green-600 dark:text-green-400">平均分数</p>
                <p className="text-3xl font-bold text-green-700 dark:text-green-300">{userProfile.averageScore}</p>
              </div>
              <Target className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-950 dark:to-purple-900">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-purple-600 dark:text-purple-400">当前等级</p>
                <p className="text-3xl font-bold text-purple-700 dark:text-purple-300">{userProfile.level}</p>
              </div>
              <Trophy className="w-8 h-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-br from-orange-50 to-orange-100 dark:from-orange-950 dark:to-orange-900">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-orange-600 dark:text-orange-400">解锁成就</p>
                <p className="text-3xl font-bold text-orange-700 dark:text-orange-300">{unlockedAchievements.length}</p>
              </div>
              <Award className="w-8 h-8 text-orange-500" />
            </div>
          </CardContent>
        </Card>
        
        {/* AI对战统计卡片 */}
        {aiBattleResults.length > 0 && (
          <Card className="bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-950 dark:to-purple-900">
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-purple-600 dark:text-purple-400">AI对战胜率</p>
                  <p className="text-3xl font-bold text-purple-700 dark:text-purple-300">{aiBattleWinRate}%</p>
                </div>
                <Sword className="w-8 h-8 text-purple-500" />
              </div>
              <div className="mt-2 text-xs text-purple-600 dark:text-purple-400">
                {aiBattleWins}/{aiBattleResults.length} 胜利
              </div>
            </CardContent>
          </Card>
        )}

        {/* 测试覆盖率统计 */}
        <Card className="bg-gradient-to-br from-cyan-50 to-cyan-100 dark:from-cyan-950 dark:to-cyan-900">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-cyan-600 dark:text-cyan-400">测试覆盖率</p>
                <p className="text-3xl font-bold text-cyan-700 dark:text-cyan-300">{Math.round((new Set(testResults.map(r => r.testType)).size / tests.length) * 100)}%</p>
              </div>
              <Target className="w-8 h-8 text-cyan-500" />
            </div>
            <div className="mt-2 text-xs text-cyan-600 dark:text-cyan-400">
              {new Set(testResults.map(r => r.testType)).size}/{tests.length} 测试已完成
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left Column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Category Performance */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Brain className="w-5 h-5" />
                能力分类表现
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              {categoryPerformance.map((category) => (
                <div key={category.category} className="space-y-2">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className={`w-3 h-3 rounded-full bg-current ${category.color}`} />
                      <span className="font-medium">{category.name}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm text-muted-foreground">
                        {category.completed}/{category.total} 完成
                      </span>
                      <Badge variant="outline" className="min-w-[60px] justify-center">
                        {category.score}分
                      </Badge>
                    </div>
                  </div>
                  <Progress value={(category.completed / category.total) * 100} className="h-3" />
                  <div className="flex justify-between text-xs text-muted-foreground">
                    <span>完成度: {Math.round((category.completed / category.total) * 100)}%</span>
                    <span>平均分: {category.score}</span>
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>

          {/* Progress Over Time */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <TrendingUp className="w-5 h-5" />
                进步趋势
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {progressData.map((week, index) => (
                  <div key={week.week} className="flex items-center justify-between p-3 bg-[rgba(234,244,255,0.6)] rounded-lg">
                    <div className="flex items-center gap-3">
                      <Calendar className="w-4 h-4 text-muted-foreground" />
                      <span className="font-medium">{week.week}</span>
                    </div>
                    <div className="flex items-center gap-4">
                      <span className="text-sm text-muted-foreground">{week.count} 次测试</span>
                      <Badge variant={week.score >= 80 ? 'default' : week.score >= 60 ? 'secondary' : 'outline'}>
                        {week.score || '无数据'}
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>
              {progressData.every(week => week.count === 0) && (
                <div className="text-center py-8 text-muted-foreground">
                  <Activity className="w-12 h-12 mx-auto mb-4 opacity-50" />
                  <p>暂无足够数据显示进步趋势</p>
                  <p className="text-sm mt-2">完成更多测试来查看您的进步</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Recent Tests */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Activity className="w-5 h-5" />
                最近测试
              </CardTitle>
            </CardHeader>
            <CardContent>
              {recentTests.length > 0 ? (
                <div className="space-y-3">
                  {recentTests.slice(0, 5).map((result, index) => (
                    <div key={index} className="flex items-center justify-between p-3 border rounded-lg">
                      <div>
                        <h4 className="font-medium flex items-center gap-2">
                          {result.testType}
                          {result.details?.battleMode && (
                            <Badge variant="outline" className="text-xs bg-purple-50 text-purple-600 border-purple-200">
                              <Bot className="w-3 h-3 mr-1" />
                              AI对战
                            </Badge>
                          )}
                        </h4>
                        <p className="text-sm text-muted-foreground">
                          {(() => {
                            const testDate = new Date(result.completedAt || result.date || result.timestamp || new Date());
                            if (testDate && !isNaN(testDate.getTime())) {
                              return testDate.toLocaleDateString('zh-CN', {
                                month: 'short',
                                day: 'numeric',
                                hour: '2-digit',
                                minute: '2-digit'
                              });
                            }
                            return '刚刚完成';
                          })()}
                        </p>
                      </div>
                      <div className="text-right">
                        <div className="text-xl font-bold text-primary">{result.score}</div>
                        {result.percentile && (
                          <div className="text-xs text-muted-foreground">
                            第{Math.round(result.percentile)}百分位
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-muted-foreground">
                  <BarChart3 className="w-12 h-12 mx-auto mb-4 opacity-50" />
                  <p>还没有测试记录</p>
                  <Button 
                    className="mt-4 bg-gradient-to-r from-slate-600 to-gray-700 hover:from-slate-700 hover:to-gray-800 text-white shadow-sm hover:shadow-md transition-all duration-200"
                    onClick={() => onStartTest('reaction')}
                  >
                    开始第一个测试
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Right Column */}
        <div className="space-y-6">
          {/* Strengths & Weaknesses */}
          {strengths.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Zap className="w-5 h-5" />
                  能力分析
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <h4 className="font-medium text-green-600 mb-2">优势项目</h4>
                  <div className="space-y-2">
                    {strengths.map((strength, index) => (
                      <div key={index} className="flex items-center justify-between p-2 bg-green-50 dark:bg-green-950 rounded">
                        <span className="text-sm">{strength.testType}</span>
                        <Badge variant="secondary" className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100">
                          {Math.round(strength.avgScore)}
                        </Badge>
                      </div>
                    ))}
                  </div>
                </div>

                <div>
                  <h4 className="font-medium text-orange-600 mb-2">提升空间</h4>
                  <div className="space-y-2">
                    {weaknesses.map((weakness, index) => (
                      <div key={index} className="flex items-center justify-between p-2 bg-orange-50 dark:bg-orange-950 rounded">
                        <span className="text-sm">{weakness.testType}</span>
                        <Badge variant="outline" className="border-orange-200 text-orange-800 dark:border-orange-800 dark:text-orange-200">
                          {Math.round(weakness.avgScore)}
                        </Badge>
                      </div>
                    ))}
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Recent Achievements */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Trophy className="w-5 h-5" />
                最新成就
              </CardTitle>
            </CardHeader>
            <CardContent>
              {unlockedAchievements.length > 0 ? (
                <div className="space-y-3">
                  {unlockedAchievements
                    .sort((a, b) => (b.unlockedDate?.getTime() || 0) - (a.unlockedDate?.getTime() || 0))
                    .slice(0, 3)
                    .map((achievement) => {
                      const Icon = achievement.icon;
                      return (
                        <div key={achievement.id} className="flex items-center gap-3 p-3 bg-yellow-50 dark:bg-yellow-950 rounded-lg">
                          <Icon className="w-6 h-6 text-yellow-500" />
                          <div className="flex-1">
                            <h4 className="font-medium">{achievement.name}</h4>
                            <p className="text-sm text-muted-foreground">{achievement.description}</p>
                            {achievement.unlockedDate && (
                              <p className="text-xs text-muted-foreground mt-1">
                                {(() => {
                                  const unlockDate = new Date(achievement.unlockedDate);
                                  if (unlockDate && !isNaN(unlockDate.getTime())) {
                                    return unlockDate.toLocaleDateString('zh-CN');
                                  }
                                  return '最近解锁';
                                })()}
                              </p>
                            )}
                          </div>
                        </div>
                      );
                    })}
                </div>
              ) : (
                <div className="text-center py-6 text-muted-foreground">
                  <Trophy className="w-8 h-8 mx-auto mb-2 opacity-50" />
                  <p className="text-sm">完成测试来解锁成就</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Quick Actions */}
          <Card>
            <CardHeader>
              <CardTitle>快速开始</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <Button 
                className="w-full bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white shadow-sm hover:shadow-md transition-all duration-200" 
                onClick={() => onStartTest('reaction')}
              >
                <Zap className="w-4 h-4 mr-2" />
                反应时间测试
              </Button>
              <Button 
                className="w-full bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
                onClick={() => onStartTest('memory')}
              >
                <Brain className="w-4 h-4 mr-2" />
                记忆力测试
              </Button>
              <Button 
                className="w-full bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
                onClick={() => onStartTest('logical')}
              >
                <Puzzle className="w-4 h-4 mr-2" />
                逻辑推理测试
              </Button>
              <Button 
                className="w-full bg-gradient-to-r from-emerald-500 to-emerald-600 hover:from-emerald-600 hover:to-emerald-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
                onClick={() => onStartTest('creative-thinking')}
              >
                <Sparkles className="w-4 h-4 mr-2" />
                创新思维测试
              </Button>
              <Button 
                className="w-full bg-gradient-to-r from-rose-500 to-rose-600 hover:from-rose-600 hover:to-rose-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
                onClick={() => onStartTest('emotion-recognition')}
              >
                <Smile className="w-4 h-4 mr-2" />
                情绪识别测试
              </Button>
              <Button 
                className="w-full bg-gradient-to-r from-indigo-500 to-indigo-600 hover:from-indigo-600 hover:to-indigo-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
                onClick={() => onStartTest('ai-battle')}
              >
                <Bot className="w-4 h-4 mr-2" />
                AI对战模式
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}